<template>
  <!-- 自定义查看图片列表弹窗 -->
  <el-dialog :title="'其他图片'" :visible.sync="dialogVisible" :close-on-click-modal="false" width="800px">
    <div class="form-box " id="copy_box">
      <div v-for="(item,ind) in list" :key="item" class="lin-item">
        <img :src="item" @click="review(ind)" />
      </div>
    </div>
    <div id="copy-btn">
      <el-button :loading="loading" class="btn" @click="copyInfo" type="primary">复制图片</el-button>
    </div>
  </el-dialog>
</template>

<script>
// import ClipboardJS from "../../../assets/js/clipboard.min.js";
// // var clipboard
// var clipboard;
export default {
  name: "imagesView",
  data() {
    return {
      dialogVisible: false,
      list: [],
      loading:false
    };
  },
  created() {},
  mounted() {

  },
  methods: {
    // 打开弹窗
    open(data) {
      this.list = [];
      this.dialogVisible = true;
      this.list = data;
      // this.$nextTick(()=>{

      //   this.copyInfo()
      // })
    },
    async copyInfo() {
      // this.copyWechatImages(this.list);
      this.copyAsMergedImage();
    },
    // async copyWechatImages(imageUrls) {
    //   try {
    //     const blobs = await this.fetchImageBlobs(imageUrls);
    //     console.log("%c Line:83 🌶 blobs", "color:#93c0a4", blobs);
    //     const clipboardItems = [];
    //     if (blobs.length) {
    //       for (let i = 0; i < blobs.length; i++) {
    //         const blob = blobs[i];
    //         const img = await createImageBitmap(blob);
    //         const canvas = new OffscreenCanvas(img.width, img.height);
    //         const ctx = canvas.getContext("2d");
    //         ctx.drawImage(img, 0, 0);

    //         // 生成 PNG Blob
    //         const pngBlob = await canvas.convertToBlob({ type: "image/png" });
    //         console.log("%c Line:95 🥟 pngBlob", "color:#6ec1c2", pngBlob);
    //         clipboardItems.push(new ClipboardItem({ "image/png": pngBlob }));
    //       }
    //     }
    //     await navigator.clipboard.write(clipboardItems);
    //     alert("复制成功！可粘贴至微信");
    //   } catch (err) {
    //     console.log("%c Line:89 🍆 err", "color:#fca650", err);
    //     // this.fallbackCopy(imageUrls); // 降级方案
    //   }
    // },
    async copyAsMergedImage() {
      this.loading = true
      try {
        // 1. 合并图片到 Canvas
        const canvas = document.createElement("canvas");
        const images = await Promise.all(
          this.list.map(
            (url) =>
              new Promise((resolve) => {
                const img = new Image();
                img.crossOrigin = "anonymous";
                img.src = url;
                img.onload = () => resolve(img);
              })
          )
        );
        canvas.width = Math.max(...images.map((img) => img.width));
        canvas.height = images.reduce(
          (sum, img) => sum + (canvas.width / img.width) * img.height,
          0
        );
        const ctx = canvas.getContext("2d");
        let yPos = 0;
        images.forEach((img) => {
          ctx.drawImage(
            img,
            0,
            yPos,
            canvas.width,
            (canvas.width / img.width) * img.height
          );
          yPos += (canvas.width / img.width) * img.height;
        });

        // 2. 转换为 Blob 写入剪贴板
        canvas.toBlob(async (blob) => {
          await navigator.clipboard.write([
            new ClipboardItem({ [blob.type]: blob }),
          ]);
          this.loading = false
          this.$message.success("合并图片复制成功");
        }, "image/png");
      } catch (error) {
        this.loading = false
      }
    },

    async fetchImageBlobs(urls) {
      return Promise.all(
        urls.map(async (url) => {
          const response = await fetch(url);

          return response.blob();
        })
      );
    },
    review(ind) {
      this.$viewerApi({
        images: this.list,
        options: {
          initialViewIndex: ind,
        },
      });
    },
  },
};
</script>
<style scoped lang="scss">
.form-box {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  .lin-item {
    width: 400px;
  }
  padding-bottom: 60px;
}
.lin-item ::v-deep .el-image {
  width: 100%;
}
#copy-btn {
  width: 100%;
  height: 60px;
  position: absolute;
  bottom: 0;
  background: #fff;
  text-align: center;
  padding-top: 15px;
}
</style>
